package com.supcalls;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import java.io.*;

public class IoUtilExample {
    public static void main(String[] args) {

        // 使用绝对路径
        String filePath = System.getProperty("user.dir") + "/example.txt";
        String destPath = System.getProperty("user.dir") + "/example_copy.txt";

        FileUtil.touch(filePath);
        FileUtil.touch(destPath);
        // 写入内容
        writeFile(filePath, "Hello, Hutool!");

        // 读取内容
        String readContent = readFile(filePath);
        System.out.println("File content: " + readContent);

        // 拷贝文件
        copyFile(filePath, destPath);
        System.out.println("File copied to " + destPath);
    }

    public static void writeFile(String filePath, String content) {
        File file = FileUtil.touch(filePath);
        System.out.println("File exists after touch: " + file.exists());

        try (FileOutputStream fos = new FileOutputStream(file)) {
            IoUtil.writeUtf8(fos, false, content);
            fos.flush();  // **手动刷新，确保数据写入磁盘**
            System.out.println("Content written to " + filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            System.err.println("Error: File not found -> " + filePath);
            return "";
        }
        try (InputStream is = new FileInputStream(file)) {
            return IoUtil.readUtf8(is);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void copyFile(String sourcePath, String destPath) {
        File sourceFile = new File(sourcePath);
        File destFile = new File(destPath);

        if (!sourceFile.exists()) {
            System.err.println("Error: Source file not found -> " + sourcePath);
            return;
        }

        try (InputStream is = new FileInputStream(sourceFile);
             OutputStream os = new FileOutputStream(destFile)) {
            IoUtil.copy(is, os);
            System.out.println("File copied to " + destPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
